<template>
  <div class="singer-wrapper" ref='singerWrapper'>
    <list-view :datalist='singerList' v-if="singerList.length" @select='selectSinger' ref='listView'></list-view>
    <router-view></router-view>
  </div>
</template>
<script>
import listView from '@/base/listview';
import Singer from '@/common/js/singer';
import { getSingerList } from '@/api/singer';
import { playlistMixin } from '@/common/js/mixin';
import { mapMutations } from 'vuex';

const HOT_NUM = 10;
const HOT_TITLE = '热门';
const PLAYER_HEIGHT = 60;

export default {
  name: 'singer',
  data() {
    return {
      singerList: [],
    };
  },
  methods: {
    // todo
    // mixin
    handlePlayList(list) {
      if (list.length > 0) {
        this.$refs.singerWrapper.style.bottom = `${PLAYER_HEIGHT}px`;
      } else {
        this.$refs.singerWrapper.style.bottom = 0;
      }
      this.$refs.listView && this.$refs.listView.refresh();
    },
    selectSinger(singer) {
      this.$router.push({
        path: `/singer/${singer.id}`,
      });
      // 对应到mapMutations
      this.setSinger(singer);
    },
    _getSingerList() {
      getSingerList().then((res) => {
        this.singerList = this._normalizeSinger(res.list);
      });
    },
    _normalizeSinger(list) {
      const map = {
        hot: {
          title: HOT_TITLE,
          items: [],
        },
      };
      list.forEach((item, index) => {
        if (index < HOT_NUM) {
          map.hot.items.push(new Singer({
            id: item.Fsinger_mid,
            name: item.Fsinger_name,
          }));
        }
        const key = item.Findex;
        if (!map[key]) {
          map[key] = {
            title: key,
            items: [],
          };
        }
        map[key].items.push(new Singer({
          id: item.Fsinger_mid,
          name: item.Fsinger_name,
        }));
      });
      const ret = [];
      const hot = [];
      Object.keys(map).forEach((attr) => {
        const val = map[attr];
        if (HOT_TITLE === val.title) {
          hot.push(val);
        }
        if (val.title.match(/[a-zA-Z]/)) {
          ret.push({
            title: attr,
            items: val.items,
          });
        }
        ret.sort((a, b) => {
          return a.title.charCodeAt(0) - b.title.charCodeAt(0);
        });
      });
      return hot.concat(ret);
    },
    ...mapMutations({
      setSinger: 'SET_SINGER',
    }),
  },
  components: {
    listView,
  },
  created() {
    this._getSingerList();
  },
  mixins: [playlistMixin],
};
</script>
<style lang='stylus' scoped>
.singer-wrapper
  position fixed
  overflow hidden
  background #222
  top 88px
  bottom 0
  left 0
  right 0
</style>
